<template>
  <div style="height: 100vh; overflow: hidden">
    <!-- 顶部工具栏 -->
    <div style="height: 60px; background: #fff; border-bottom: 1px solid #e1e6f0; display: flex; align-items: center; justify-content: space-between; padding: 0 20px;" v-if="!showTemplateSelection">
      <div class="toolbar-left">
        <h3>微信小程序可视化编辑器</h3>
        <div class="campus-info" v-if="!isLoading">
          <span class="campus-label">当前校区：</span>
          <!-- 只有超级管理员才能选择校区 -->
          <el-select
            v-if="isAdmin"
            v-model="currentCampusId"
            placeholder="选择校区"
            @change="handleCampusChange"
            size="small"
            style="width: 200px;"
          >
            <el-option
              label="全部校区（超级管理员）"
              :value="null"
            />
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId"
              :label="campus.campusName"
              :value="campus.campusId"
            />
          </el-select>
          <!-- 普通校区用户只显示校区名，不能更改 -->
          <el-tag v-else type="success" size="small">
            {{ currentCampus ? currentCampus.campusName : '未知校区' }}
          </el-tag>
          <el-tag v-if="isAdmin && currentCampus" type="success" size="small" style="margin-left: 8px;">
            {{ currentCampus.campusName }}
          </el-tag>
          <el-tag v-else-if="isAdmin" type="warning" size="small" style="margin-left: 8px;">
            超级管理员模式
          </el-tag>
        </div>
      </div>
      <div class="toolbar-right">
        <el-button @click="backToTemplateSelection" icon="el-icon-back" size="small">返回模板选择</el-button>
        <el-button @click="refreshData" icon="el-icon-refresh" size="small">刷新数据</el-button>
        <el-button @click="saveCurrentTemplate" type="success" icon="el-icon-check">保存模板</el-button>
        <el-button @click="createNewTemplate" type="primary" icon="el-icon-plus">新建模板</el-button>
        <el-button type="info" @click="previewMiniProgram">预览小程序</el-button>
        <el-button type="warning" @click="generateCode">生成代码</el-button>
      </div>
    </div>

        <!-- 模板选择界面 -->
    <div v-if="showTemplateSelection" style="padding: 20px;">
      <div style="margin-bottom: 20px;">
        <h3>选择首页模板 - {{ currentCampus ? currentCampus.campusName : '未知校区' }}</h3>
        <el-button @click="createNewTemplate" type="primary" style="float: right;">新建模板</el-button>
        <div style="clear: both;"></div>
      </div>

      <div v-loading="templateCardsLoading">
        <div style="display: flex; flex-wrap: wrap; gap: 20px;">
          <div
            v-for="template in templateCards"
            :key="template.id"
            style="width: 300px; border: 1px solid #ddd; border-radius: 8px; padding: 15px; cursor: pointer; background: white;"
            @click="selectTemplate(template)"
          >
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
              <h4 style="margin: 0;">{{ template.templateName }}</h4>
              <el-tag v-if="template.isActive" type="success" size="mini">已启用</el-tag>
            </div>

            <div style="height: 120px; background: #f5f5f5; border-radius: 4px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
              <div style="text-align: center; color: #999;">
                <i class="el-icon-monitor" style="font-size: 36px; display: block; margin-bottom: 5px;"></i>
                <span>首页预览</span>
              </div>
            </div>

            <p style="color: #666; font-size: 14px; margin: 0 0 10px 0;">{{ template.templateDesc || '暂无描述' }}</p>

            <div style="display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: #999;">
              <span><i class="el-icon-user"></i> {{ template.createBy }}</span>
              <span><i class="el-icon-time"></i> {{ formatTime(template.createTime) }}</span>
            </div>

            <div style="margin-top: 10px; display: flex; justify-content: space-between;">
              <el-button type="primary" size="mini" @click.stop="selectTemplate(template)">编辑</el-button>
              <el-dropdown @command="handleTemplateAction" trigger="click" @click.stop>
                <el-button size="mini">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{action: 'copy', template}">复制</el-dropdown-item>
                  <el-dropdown-item v-if="!template.isActive" :command="{action: 'activate', template}">启用</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', template}">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="templateCards.length === 0 && !templateCardsLoading" style="text-align: center; padding: 50px;">
          <i class="el-icon-folder-opened" style="font-size: 64px; color: #ccc;"></i>
          <h3>暂无模板</h3>
          <p>还没有创建任何首页模板</p>
          <el-button @click="createNewTemplate" type="primary">创建第一个模板</el-button>
        </div>
      </div>
    </div>

    <div v-else style="display: flex; height: calc(100vh - 60px);">
      <!-- 左侧组件库 -->
      <div style="width: 240px; background: #fff; border-right: 1px solid #e1e6f0; overflow-y: auto;">
        <div style="padding: 20px;">
          <h3 style="margin: 0 0 20px 0; color: #2c3e50; font-size: 16px;">组件库</h3>
          <div>
            <div
              v-for="component in componentList"
              :key="component.type"
              style="display: flex; align-items: center; padding: 12px 16px; margin-bottom: 8px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; cursor: pointer; transition: all 0.3s ease;"
              @click="addComponent(component.type)"
            >
              <i :class="component.icon" style="margin-right: 12px; font-size: 18px; color: #409eff;"></i>
              <span style="font-size: 14px; color: #2c3e50;">{{ component.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间画布区域 -->
      <div style="flex: 1; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); display: flex; justify-content: center; align-items: center; padding: 20px;">
        <div style="width: 375px; height: 667px; background: #1a1a1a; border-radius: 30px; padding: 15px;">
          <div style="height: 30px; display: flex; justify-content: space-between; align-items: center; color: #fff; font-size: 12px; padding: 0 20px; background: rgba(255,255,255,0.1); border-radius: 15px 15px 0 0;">
            <span>9:41</span>
            <span>100%</span>
          </div>

          <div style="width: 345px; height: 622px; background: #fff; border-radius: 0 0 15px 15px; overflow-y: auto;" @click="handleCanvasClick">
            <draggable
              v-model="pageComponents"
              group="components"
              @end="onDragEnd"
              style="min-height: 100%; padding: 10px;"
              :animation="200"
            >
              <component-wrapper
                v-for="(item, index) in pageComponents"
                :key="item.id"
                :component="item"
                :is-selected="selectedComponentIndex === index"
                :selected-banners="selectedBanners"
                :selected-entries="selectedEntries"
                :selected-goods="selectedGoods"
                :selected-recommends="selectedRecommends"
                :selected-quicks="selectedQuicks"
                :selected-campus-ads="selectedCampusAds"
                :selected-distribution-goods="selectedDistributionGoods"
                :campus-list="campusList"
                @select="selectComponent(item, index)"
                @delete="deleteComponent(index)"
                @update="updateComponent"
                @debug="(msg) => console.log('ComponentWrapper Debug:', msg)"
              />
            </draggable>
          </div>
        </div>
      </div>

      <!-- 右侧配置面板 -->
      <div style="width: 320px; background: #fff; border-left: 1px solid #e1e6f0; overflow-y: auto;">
        <div class="config-panel">
          <div v-if="!selectedComponent" class="no-selection">
            <i class="el-icon-mouse"></i>
            <p>请选择一个组件进行配置</p>
            <small>点击左侧组件库添加组件，或点击画布中的组件进行编辑</small>
          </div>

          <div v-else class="component-config">
            <div class="config-header">
              <h3>
                <i :class="getComponentIcon(selectedComponent.type)"></i>
                {{ getComponentName(selectedComponent.type) }}
              </h3>
              <el-button @click="deleteSelectedComponent" type="danger" size="mini">
                <i class="el-icon-delete"></i>
              </el-button>
            </div>

            <!-- 轮播图配置 -->
            <div v-if="selectedComponent.type === 'banner'" class="config-section">
              <h4><i class="el-icon-picture"></i> 轮播图设置</h4>
              <el-button @click="manageBanners" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理轮播图 ({{ selectedBanners.length }}张)
              </el-button>
              <div class="banner-preview" v-if="selectedBanners.length > 0">
                <div
                  v-for="banner in selectedBanners"
                  :key="banner.id"
                  class="banner-item"
                >
                  <image-preview :src="banner.image || banner.imageUrl || '/default-banner.jpg'" :width="50" :height="35"/>
                  <div class="banner-info">
                    <span class="banner-title">{{ banner.title }}</span>
                    <small class="banner-link">{{ banner.link || '无链接' }}</small>
                  </div>
                </div>
              </div>

              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="自动播放">
                  <el-switch v-model="selectedComponent.data.autoPlay" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="播放间隔">
                  <el-input-number
                    v-model="selectedComponent.data.interval"
                    :min="1000"
                    :max="10000"
                    :step="500"
                    @change="updateComponent"
                  />
                  <small>毫秒</small>
                </el-form-item>
              </el-form>
            </div>

            <!-- 校区配置 -->
            <div v-if="selectedComponent.type === 'campus'" class="config-section">
              <h4><i class="el-icon-office-building"></i> 校区设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="选择校区">
                  <el-select v-model="selectedComponent.data.campusId" placeholder="选择校区" @change="updateComponent">
                    <el-option
                      v-for="campus in campusList"
                      :key="campus.campusId"
                      :label="campus.campusName"
                      :value="campus.campusId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="显示Logo">
                  <el-switch v-model="selectedComponent.data.showLogo" @change="updateComponent" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 搜索框配置 -->
            <div v-if="selectedComponent.type === 'search'" class="config-section">
              <h4><i class="el-icon-search"></i> 搜索框设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="占位符">
                  <el-input v-model="selectedComponent.data.placeholder" @input="updateComponent" />
                </el-form-item>
                <el-form-item label="搜索类型">
                  <el-select v-model="selectedComponent.data.searchType" @change="updateComponent">
                    <el-option label="全部" value="all" />
                    <el-option label="课程" value="course" />
                    <el-option label="商品" value="goods" />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>

            <!-- 图片配置 -->
            <div v-if="selectedComponent.type === 'image'" class="config-section">
              <h4><i class="el-icon-picture-outline"></i> 图片设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="图片链接">
                  <el-input v-model="selectedComponent.data.src" @input="updateComponent" placeholder="输入图片URL" />
                </el-form-item>
                <el-form-item label="图片描述">
                  <el-input v-model="selectedComponent.data.alt" @input="updateComponent" placeholder="图片描述文字" />
                </el-form-item>
                <el-form-item label="宽度">
                  <el-input-number
                    v-model="selectedComponent.data.width"
                    :min="10"
                    :max="100"
                    @change="updateComponent"
                  />
                  <small>%</small>
                </el-form-item>
                <el-form-item label="高度">
                  <el-input-number
                    v-model="selectedComponent.data.height"
                    :min="50"
                    :max="500"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
                <el-form-item label="显示模式">
                  <el-select v-model="selectedComponent.data.objectFit" @change="updateComponent">
                    <el-option label="适应容器" value="contain" />
                    <el-option label="填充容器" value="cover" />
                    <el-option label="保持原始" value="none" />
                    <el-option label="拉伸填充" value="fill" />
                  </el-select>
                </el-form-item>
                <el-form-item label="可点击">
                  <el-switch v-model="selectedComponent.data.clickable" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="点击链接" v-if="selectedComponent.data.clickable">
                  <el-input v-model="selectedComponent.data.link" @input="updateComponent" placeholder="点击跳转的链接" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 视频配置 -->
            <div v-if="selectedComponent.type === 'video'" class="config-section">
              <h4><i class="el-icon-video-camera"></i> 视频设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="视频链接">
                  <el-input v-model="selectedComponent.data.src" @input="updateComponent" placeholder="输入视频URL" />
                </el-form-item>
                <el-form-item label="封面图片">
                  <el-input v-model="selectedComponent.data.poster" @input="updateComponent" placeholder="视频封面图片URL" />
                </el-form-item>
                <el-form-item label="宽度">
                  <el-input-number
                    v-model="selectedComponent.data.width"
                    :min="10"
                    :max="100"
                    @change="updateComponent"
                  />
                  <small>%</small>
                </el-form-item>
                <el-form-item label="高度">
                  <el-input-number
                    v-model="selectedComponent.data.height"
                    :min="100"
                    :max="500"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
                <el-form-item label="自动播放">
                  <el-switch v-model="selectedComponent.data.autoplay" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="循环播放">
                  <el-switch v-model="selectedComponent.data.loop" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="静音播放">
                  <el-switch v-model="selectedComponent.data.muted" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="显示控件">
                  <el-switch v-model="selectedComponent.data.controls" @change="updateComponent" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 文本配置 -->
            <div v-if="selectedComponent.type === 'text'" class="config-section">
              <h4><i class="el-icon-edit-outline"></i> 文本设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="文本内容">
                  <el-input
                    type="textarea"
                    v-model="selectedComponent.data.content"
                    @input="updateComponent"
                    :rows="3"
                  />
                </el-form-item>
                <el-form-item label="文本对齐">
                  <el-radio-group v-model="selectedComponent.style.textAlign" @change="updateComponent">
                    <el-radio-button label="left">左对齐</el-radio-button>
                    <el-radio-button label="center">居中</el-radio-button>
                    <el-radio-button label="right">右对齐</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>

            <!-- 商品展示配置 -->
            <div v-if="selectedComponent.type === 'goods'" class="config-section">
              <h4><i class="el-icon-goods"></i> 商品设置</h4>
              <el-button @click="manageGoods" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理商品
              </el-button>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="显示布局">
                  <el-radio-group v-model="selectedComponent.data.layout" @change="updateComponent">
                    <el-radio-button label="grid">网格</el-radio-button>
                    <el-radio-button label="list">列表</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="列数" v-if="selectedComponent.data.layout === 'grid'">
                  <el-input-number
                    v-model="selectedComponent.data.columns"
                    :min="1"
                    :max="3"
                    @change="updateComponent"
                  />
                </el-form-item>
              </el-form>
            </div>

            <!-- 分销商品配置 -->
            <div v-if="selectedComponent.type === 'distribution-goods'" class="config-section">
              <h4><i class="el-icon-share"></i> 分销商品设置</h4>
              <el-button @click="manageDistributionGoods" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理分销商品 ({{ selectedDistributionGoods.length }}个)
              </el-button>
              <div class="distribution-preview" v-if="selectedDistributionGoods.length > 0">
                <div
                  v-for="goods in selectedDistributionGoods.slice(0, 3)"
                  :key="goods.goodId"
                  class="distribution-item"
                >
                  <img :src="goods.goodPicture || '/images/placeholder.jpg'" :alt="goods.goodName" />
                  <div class="distribution-info">
                    <span class="goods-title">{{ goods.goodName }}</span>
                    <small class="goods-source">来自: {{ getCampusName(goods.campusId) }}</small>
                  </div>
                </div>
                <div v-if="selectedDistributionGoods.length > 3" class="more-info">
                  还有 {{ selectedDistributionGoods.length - 3 }} 个商品...
                </div>
              </div>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="显示布局">
                  <el-radio-group v-model="selectedComponent.data.layout" @change="updateComponent">
                    <el-radio-button label="grid">网格</el-radio-button>
                    <el-radio-button label="list">列表</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="列数" v-if="selectedComponent.data.layout === 'grid'">
                  <el-input-number
                    v-model="selectedComponent.data.columns"
                    :min="1"
                    :max="3"
                    @change="updateComponent"
                  />
                </el-form-item>

                <el-form-item label="混合显示">
                  <el-switch v-model="selectedComponent.data.mixedDisplay" @change="updateComponent" />
                  <small>开启后本校区商品和分销商品混合显示</small>
                </el-form-item>
              </el-form>
            </div>

            <!-- 快捷入口配置 -->
            <div v-if="selectedComponent.type === 'quick'" class="config-section">
              <h4><i class="el-icon-menu"></i> 快捷入口设置</h4>
              <el-button @click="manageQuickEntries" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理快捷入口
              </el-button>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="显示布局">
                  <el-radio-group v-model="selectedComponent.data.layout" @change="updateComponent">
                    <el-radio-button label="horizontal">横向</el-radio-button>
                    <el-radio-button label="vertical">纵向</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>

            <!-- 功能入口配置 -->
            <div v-if="selectedComponent.type === 'entries'" class="config-section">
              <h4><i class="el-icon-s-grid"></i> 功能入口设置</h4>
              <el-button @click="manageFunctionEntries" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理功能入口
              </el-button>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="每行显示">
                  <el-input-number
                    v-model="selectedComponent.data.columns"
                    :min="2"
                    :max="5"
                    @change="updateComponent"
                  />
                </el-form-item>
                <el-form-item label="显示标题">
                  <el-switch v-model="selectedComponent.data.showTitle" @change="updateComponent" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 校区公告配置 -->
            <div v-if="selectedComponent.type === 'notice'" class="config-section">
              <h4><i class="el-icon-bell"></i> 校区公告设置</h4>
              <el-button @click="manageCampusAds" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理校区公告 ({{ selectedCampusAds.length }}条)
              </el-button>
              <div class="campus-preview" v-if="selectedCampusAds.length > 0">
                <div
                  v-for="campus in selectedCampusAds.slice(0, 3)"
                  :key="campus.id"
                  class="campus-item"
                >
                  <div class="campus-info">
                    <span class="campus-title">{{ campus.title }}</span>
                    <small class="campus-tag">{{ campus.tag || '通用公告' }}</small>
                  </div>
                </div>
                <div v-if="selectedCampusAds.length > 3" class="more-info">
                  还有 {{ selectedCampusAds.length - 3 }} 条公告...
                </div>
              </div>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="显示时间">
                  <el-switch v-model="selectedComponent.data.showTime" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="公告类型">
                  <el-select v-model="selectedComponent.data.type" @change="updateComponent">
                    <el-option label="普通公告" value="normal" />
                    <el-option label="重要公告" value="important" />
                    <el-option label="紧急公告" value="urgent" />
                  </el-select>
                </el-form-item>
                <el-form-item label="最大显示">
                  <el-input-number
                    v-model="selectedComponent.data.maxCount"
                    :min="1"
                    :max="10"
                    @change="updateComponent"
                  />
                  <small>条公告</small>
                </el-form-item>
              </el-form>
            </div>

            <!-- 品牌推荐配置 -->
            <div v-if="selectedComponent.type === 'recommend'" class="config-section">
              <h4><i class="el-icon-star-on"></i> 品牌推荐设置</h4>
              <el-button @click="manageBrandRecommend" type="primary" size="small" class="manage-btn">
                <i class="el-icon-setting"></i>
                管理推荐品牌
              </el-button>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="显示布局">
                  <el-radio-group v-model="selectedComponent.data.layout" @change="updateComponent">
                    <el-radio-button label="horizontal">横向滚动</el-radio-button>
                    <el-radio-button label="grid">网格显示</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="显示Logo">
                  <el-switch v-model="selectedComponent.data.showLogo" @change="updateComponent" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 样式配置 -->
            <div class="config-section">
              <h4><i class="el-icon-brush"></i> 样式设置</h4>
              <el-form label-width="80px" size="small" class="config-form">
                <el-form-item label="背景色" v-if="!['image', 'video'].includes(selectedComponent.type)">
                  <el-color-picker v-model="selectedComponent.style.backgroundColor" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="文字颜色" v-if="!['banner', 'image', 'video'].includes(selectedComponent.type)">
                  <el-color-picker v-model="selectedComponent.style.color" @change="updateComponent" />
                </el-form-item>
                <el-form-item label="字体大小" v-if="!['banner', 'image', 'video'].includes(selectedComponent.type)">
                  <el-input-number
                    v-model="selectedComponent.style.fontSize"
                    :min="12"
                    :max="32"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
                <el-form-item label="圆角">
                  <el-input-number
                    v-model="selectedComponent.style.borderRadius"
                    :min="0"
                    :max="20"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
                <el-form-item label="内边距" v-if="!['image', 'video'].includes(selectedComponent.type)">
                  <el-input-number
                    v-model="selectedComponent.style.padding"
                    :min="0"
                    :max="30"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
                <el-form-item label="外边距">
                  <el-input-number
                    v-model="selectedComponent.style.margin"
                    :min="0"
                    :max="30"
                    @change="updateComponent"
                  />
                  <small>px</small>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 轮播图管理弹窗 -->
    <el-dialog title="轮播图管理" :visible.sync="bannerDialogVisible" width="80%" class="manage-dialog">
      <banner-manager
        :selected="selectedBanners"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleBannerSelect"
        @close="bannerDialogVisible = false"
      />
    </el-dialog>

    <!-- 功能入口管理弹窗 -->
    <el-dialog title="功能入口管理" :visible.sync="entriesDialogVisible" width="80%" class="manage-dialog">
      <entries-manager
        :selected="selectedEntries"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleEntriesSelect"
        @close="entriesDialogVisible = false"
      />
    </el-dialog>

    <!-- 商品管理弹窗 -->
    <el-dialog title="商品管理" :visible.sync="goodsDialogVisible" width="80%" class="manage-dialog">
      <goods-manager
        :selected="selectedGoods"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleGoodsSelect"
        @close="goodsDialogVisible = false"
      />
    </el-dialog>

    <!-- 品牌推荐管理弹窗 -->
    <el-dialog title="品牌推荐管理" :visible.sync="recommendDialogVisible" width="80%" class="manage-dialog">
      <recommend-manager
        :selected="selectedRecommends"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleRecommendSelect"
        @close="recommendDialogVisible = false"
      />
    </el-dialog>

    <!-- 快捷入口管理弹窗 -->
    <el-dialog title="快捷入口管理" :visible.sync="quickDialogVisible" width="80%" class="manage-dialog">
      <quick-manager
        :selected="selectedQuicks"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleQuickSelect"
        @close="quickDialogVisible = false"
      />
    </el-dialog>

    <!-- 校区公告管理弹窗 -->
    <el-dialog title="校区公告管理" :visible.sync="campusDialogVisible" width="80%" class="manage-dialog">
      <campus-manager
        :selected="selectedCampusAds"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleCampusSelect"
        @close="campusDialogVisible = false"
      />
    </el-dialog>

    <!-- 分销商品管理弹窗 -->
    <el-dialog title="分销商品管理" :visible.sync="distributionGoodsDialogVisible" width="90%" class="manage-dialog">
      <distribution-goods-manager
        :selected="selectedDistributionGoods"
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @select="handleDistributionGoodsSelect"
        @close="distributionGoodsDialogVisible = false"
      />
    </el-dialog>

    <!-- 代码生成预览弹窗 -->
    <el-dialog title="小程序代码预览" :visible.sync="codeDialogVisible" width="90%" class="code-dialog">
      <code-preview :page-data="pageData" />
    </el-dialog>

    <!-- 模板管理弹窗 -->
    <el-dialog title="首页模板管理" :visible.sync="templateDialogVisible" width="80%" class="template-dialog">
      <template-manager
        :current-campus-id="currentCampusId"
        :is-admin="isAdmin"
        :campus-list="campusList"
        @load-template="handleLoadTemplate"
        @close="templateDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import BannerManager from './components/BannerManager.vue'
import EntriesManager from './components/EntriesManager.vue'
import GoodsManager from './components/GoodsManager.vue'
import RecommendManager from './components/RecommendManager.vue'
import QuickManager from './components/QuickManager.vue'
import CampusManager from './components/CampusManager.vue'
import CodePreview from './components/CodePreview.vue'
import ComponentWrapper from './components/ComponentWrapper.vue'
import DistributionGoodsManager from './components/DistributionGoodsManager.vue'
import TemplateManager from './components/TemplateManager.vue'
import { listCampusInfo } from '@/api/campus/campusInfo'
import { listBannerAds } from '@/api/home/bannerAds/bannerAds'
import { getHomeData, getCampusList, getBannersByCampus, getGoodsByCampus, getCampusIdFromCookie, getUserFromCookie } from '@/api/home/management'
import { listHomepageTemplate, addHomepageTemplate, updateHomepageTemplate, delHomepageTemplate, activateTemplate, copyTemplate } from '@/api/home/template'

export default {
  name: "MiniprogramDesigner",
  components: {
    draggable,
    BannerManager,
    EntriesManager,
    GoodsManager,
    RecommendManager,
    QuickManager,
    CampusManager,
    CodePreview,
    ComponentWrapper,
    DistributionGoodsManager,
    TemplateManager
  },
  data() {
    return {
      // 界面控制
      showTemplateSelection: true, // 是否显示模板选择界面
      currentTemplateId: null, // 当前编辑的模板ID

      // 模板卡片
      templateCards: [],
      templateCardsLoading: false,
      templateSearchName: '',

      // 组件库
      componentList: [
        { type: 'campus', name: '校区名称', icon: 'el-icon-office-building' },
        { type: 'search', name: '搜索框', icon: 'el-icon-search' },
        { type: 'banner', name: '轮播图', icon: 'el-icon-picture' },
        { type: 'image', name: '图片', icon: 'el-icon-picture-outline' },
        { type: 'video', name: '视频', icon: 'el-icon-video-camera' },
        { type: 'goods', name: '外链商品', icon: 'el-icon-goods' },
        { type: 'distribution-goods', name: '分销商品', icon: 'el-icon-share' },
        { type: 'quick', name: '快捷入口', icon: 'el-icon-menu' },
        { type: 'entries', name: '功能入口', icon: 'el-icon-s-grid' },
        { type: 'notice', name: '校区公告', icon: 'el-icon-bell' },
        { type: 'recommend', name: '品牌推荐', icon: 'el-icon-star-on' },
        { type: 'text', name: '文本', icon: 'el-icon-edit-outline' }
      ],

      // 页面组件
      pageComponents: [],
      selectedComponent: null,
      selectedComponentIndex: -1,

      // 数据源
      campusList: [],
      selectedBanners: [],
      selectedEntries: [],
      selectedGoods: [],
      selectedRecommends: [],
      selectedQuicks: [],
      selectedCampusAds: [],
      selectedDistributionGoods: [],

      // 校区相关
      currentCampusId: null,
      currentCampus: null,
      isAdmin: false,
      isLoading: true,

      // 弹窗控制
      bannerDialogVisible: false,
      entriesDialogVisible: false,
      goodsDialogVisible: false,
      recommendDialogVisible: false,
      quickDialogVisible: false,
      campusDialogVisible: false,
      codeDialogVisible: false,
      distributionGoodsDialogVisible: false,
      templateDialogVisible: false,

      // 页面数据
      pageData: {
        components: [],
        config: {}
      }
    }
  },
  mounted() {
    this.initializePage()
  },
  methods: {
    // 初始化页面
    async initializePage() {
      this.isLoading = true
      try {
        // 获取Cookie中的校区ID
        this.currentCampusId = this.getCampusIdFromCookie()
        this.isAdmin = this.currentCampusId === null

        // 加载校区列表
        await this.loadCampusList()

        // 设置当前校区
        if (this.currentCampusId && this.campusList.length > 0) {
          this.currentCampus = this.campusList.find(campus => campus.campusId === this.currentCampusId)
        }

        // 加载模板卡片
        await this.loadTemplateCards()

        this.isLoading = false
      } catch (error) {
        console.error('初始化页面失败:', error)
        this.isLoading = false
      }
    },

    // 获取Cookie中的校区ID（从user对象中读取）
    getCampusIdFromCookie() {
      return getCampusIdFromCookie()
    },

    // 获取用户信息
    getUserFromCookie() {
      return getUserFromCookie()
    },

    // 处理校区切换
    async handleCampusChange(campusId) {
      this.currentCampusId = campusId
      this.isAdmin = campusId === null

      // 更新当前校区信息
      if (campusId && this.campusList.length > 0) {
        this.currentCampus = this.campusList.find(campus => campus.campusId === campusId)
      } else {
        this.currentCampus = null
      }

      // 设置Cookie
      if (campusId) {
        this.$cookies.set('campusId', campusId, '7d')
      } else {
        this.$cookies.remove('campusId')
      }

      // 刷新数据
      await this.refreshData()

      this.$message.success(`已切换到${this.currentCampus ? this.currentCampus.campusName : '超级管理员模式'}`)
    },

    // 刷新数据
    async refreshData() {
      // 清空当前选中的数据
      this.selectedBanners = []
      this.selectedEntries = []
      this.selectedGoods = []
      this.selectedRecommends = []
      this.selectedQuicks = []
      this.selectedCampusAds = []

      // 重新加载组件数据
      await this.loadAllComponentData()

      this.$message.success('数据已刷新')
    },

    // 加载校区列表
    async loadCampusList() {
      try {
        console.log('开始加载校区列表...')

        // 先尝试使用主接口
        const response = await getCampusList()
        console.log('getCampusList响应:', response)

        // 尝试不同的数据结构
        let campusData = response.data || response.rows || []

        if (campusData.length > 0) {
          this.campusList = campusData
          console.log('成功加载校区列表:', this.campusList)
        } else {
          console.warn('主接口返回空数据，尝试备用接口...')

          // 如果主接口失败，尝试使用旧接口
          const fallbackResponse = await listCampusInfo()
          console.log('listCampusInfo响应:', fallbackResponse)

          this.campusList = fallbackResponse.rows || fallbackResponse.data || []
          console.log('备用接口校区列表:', this.campusList)
        }

        if (this.campusList.length === 0) {
          console.warn('所有接口都返回空数据')
          this.$message.warning('暂无校区数据')
        }

      } catch (error) {
        console.error('加载校区列表失败:', error)
        this.$message.error('加载校区列表失败: ' + error.message)

        // 最后的备用方案：使用模拟数据
        this.campusList = [
          {
            campusId: 1,
            campusName: '测试校区1',
            id: 1,
            name: '测试校区1'
          },
          {
            campusId: 2,
            campusName: '测试校区2',
            id: 2,
            name: '测试校区2'
          }
        ]
        console.log('使用模拟校区数据:', this.campusList)
      }
    },

    // 加载草稿
    async loadDraft() {
      const draft = localStorage.getItem('miniprogram_draft')
      if (draft) {
        try {
          const draftData = JSON.parse(draft)
          this.pageComponents = draftData.components || []

          // 恢复选中的数据
          if (draftData.selectedData) {
            this.selectedBanners = draftData.selectedData.banners || []
            this.selectedEntries = draftData.selectedData.entries || []
            this.selectedGoods = draftData.selectedData.goods || []
            this.selectedRecommends = draftData.selectedData.recommends || []
            this.selectedQuicks = draftData.selectedData.quicks || []
            this.selectedCampusAds = draftData.selectedData.campusAds || []
            this.selectedDistributionGoods = draftData.selectedData.distributionGoods || []
          }

          // 如果没有保存的数据，才加载组件相关的数据
          if (!draftData.selectedData) {
            await this.loadAllComponentData()
          }
        } catch (error) {
          console.error('加载草稿失败:', error)
        }
      }
    },

    // 加载所有组件数据
    async loadAllComponentData() {
      // 收集所有组件中使用的数据ID
      const bannerIds = new Set()
      const entryIds = new Set()
      const goodsIds = new Set()
      const recommendIds = new Set()
      const quickIds = new Set()
      const campusAdsIds = new Set()

      this.pageComponents.forEach(component => {
        switch (component.type) {
          case 'banner':
            if (component.data.banners) {
              component.data.banners.forEach(id => bannerIds.add(id))
            }
            break
          case 'entries':
            if (component.data.entries) {
              component.data.entries.forEach(id => entryIds.add(id))
            }
            break
          case 'goods':
            if (component.data.goodsIds) {
              component.data.goodsIds.forEach(id => goodsIds.add(id))
            }
            break
          case 'recommend':
            if (component.data.brands) {
              component.data.brands.forEach(id => recommendIds.add(id))
            }
            break
          case 'quick':
            if (component.data.entries) {
              component.data.entries.forEach(id => quickIds.add(id))
            }
            break
          case 'notice':
            if (component.data.campusAds) {
              component.data.campusAds.forEach(id => campusAdsIds.add(id))
            }
            break
        }
      })

      // 并行加载所有数据
      await Promise.all([
        this.loadSelectedBanners([...bannerIds]),
        this.loadSelectedEntries([...entryIds]),
        this.loadSelectedGoods([...goodsIds]),
        this.loadSelectedRecommends([...recommendIds]),
        this.loadSelectedQuicks([...quickIds]),
        this.loadSelectedCampusAds([...campusAdsIds])
      ])
    },

    // 添加组件
    addComponent(type) {
      const newComponent = {
        id: Date.now(),
        type,
        name: this.getComponentName(type),
        style: this.getDefaultStyle(type),
        data: this.getDefaultData(type)
      }

      this.pageComponents.push(newComponent)
      this.selectedComponent = newComponent
      this.selectedComponentIndex = this.pageComponents.length - 1

      this.$message.success(`${newComponent.name} 添加成功`)
    },

    // 添加默认模板
    addDefaultTemplate() {
      this.pageComponents = [
        {
          id: Date.now() + 1,
          type: 'campus',
          name: '校区名称',
          style: this.getDefaultStyle('campus'),
          data: this.getDefaultData('campus')
        },
        {
          id: Date.now() + 2,
          type: 'search',
          name: '搜索框',
          style: this.getDefaultStyle('search'),
          data: this.getDefaultData('search')
        },
        {
          id: Date.now() + 3,
          type: 'banner',
          name: '轮播图',
          style: this.getDefaultStyle('banner'),
          data: this.getDefaultData('banner')
        }
      ]
      this.$message.success('默认模板已添加')
    },

    // 获取组件默认样式
    getDefaultStyle(type) {
      const defaults = {
        campus: {
          fontSize: 18,
          color: '#333',
          backgroundColor: 'transparent',
          margin: 10,
          padding: 12,
          borderRadius: 4,
          textAlign: 'left'
        },
        search: {
          backgroundColor: '#f5f5f5',
          borderRadius: 20,
          padding: 12,
          fontSize: 14,
          color: '#666',
          margin: 15
        },
        banner: {
          backgroundColor: '#e0e0e0',
          borderRadius: 8,
          margin: 15,
          padding: 0
        },
        image: {
          backgroundColor: 'transparent',
          borderRadius: 8,
          margin: 15,
          padding: 0
        },
        video: {
          backgroundColor: '#000',
          borderRadius: 8,
          margin: 15,
          padding: 0
        },
        goods: {
          backgroundColor: '#fff',
          borderRadius: 8,
          padding: 15,
          fontSize: 14,
          color: '#333',
          margin: 15
        },
        quick: {
          backgroundColor: '#fff',
          borderRadius: 8,
          padding: 15,
          fontSize: 12,
          color: '#666',
          margin: 15
        },
        entries: {
          backgroundColor: '#fff',
          borderRadius: 8,
          padding: 15,
          fontSize: 14,
          color: '#333',
          margin: 15
        },
        notice: {
          backgroundColor: '#fff3cd',
          borderRadius: 8,
          padding: 12,
          fontSize: 14,
          color: '#856404',
          margin: 15
        },
        recommend: {
          backgroundColor: '#fff',
          borderRadius: 8,
          padding: 15,
          fontSize: 14,
          color: '#333',
          margin: 15
        },
        'distribution-goods': {
          backgroundColor: '#fff',
          borderRadius: 8,
          padding: 15,
          fontSize: 14,
          color: '#333',
          margin: 15
        },
        text: {
          fontSize: 14,
          color: '#666',
          backgroundColor: 'transparent',
          margin: 10,
          padding: 8,
          borderRadius: 4,
          textAlign: 'left'
        }
      }
      return { ...defaults[type] } || {}
    },

    // 获取组件默认数据
    getDefaultData(type) {
      const defaults = {
        campus: { campusId: null, showLogo: true },
        search: { placeholder: '搜索课程、商品...', searchType: 'all' },
        banner: { banners: [], autoPlay: true, interval: 3000 },
        image: {
          src: '/placeholder.jpg',
          alt: '图片描述',
          width: 100,
          height: 100,
          objectFit: 'cover',
          clickable: false,
          link: ''
        },
        video: {
          src: '',
          poster: '/placeholder.jpg',
          autoplay: false,
          loop: false,
          muted: false,
          controls: true,
          width: 100,
          height: 200
        },
        goods: { goodsIds: [], layout: 'grid', columns: 2 },
        'distribution-goods': { goodsIds: [], layout: 'grid', columns: 2, mixedDisplay: false },
        quick: { entries: [], layout: 'horizontal' },
        entries: { entries: [], layout: 'grid', columns: 4, showTitle: true },
        notice: { campusAds: [], showTime: true, type: 'normal', maxCount: 3 },
        recommend: { brands: [], layout: 'horizontal', showLogo: true },
        text: { content: '请输入文本内容' }
      }
      return { ...defaults[type] } || {}
    },

    // 选择组件
    selectComponent(component, index) {
      this.selectedComponent = component
      this.selectedComponentIndex = index

      // 根据组件类型加载对应的已选择数据（只有在数据不存在时才加载）
      switch (component.type) {
        case 'banner':
          if (this.selectedBanners.length === 0 && component.data.banners && component.data.banners.length > 0) {
            this.loadSelectedBanners(component.data.banners)
          }
          break
        case 'entries':
          if (this.selectedEntries.length === 0 && component.data.entries && component.data.entries.length > 0) {
            this.loadSelectedEntries(component.data.entries)
          }
          break
        case 'goods':
          if (this.selectedGoods.length === 0 && component.data.goodsIds && component.data.goodsIds.length > 0) {
            this.loadSelectedGoods(component.data.goodsIds)
          }
          break
        case 'recommend':
          if (this.selectedRecommends.length === 0 && component.data.brands && component.data.brands.length > 0) {
            this.loadSelectedRecommends(component.data.brands)
          }
          break
        case 'quick':
          if (this.selectedQuicks.length === 0 && component.data.entries && component.data.entries.length > 0) {
            this.loadSelectedQuicks(component.data.entries)
          }
          break
        case 'notice':
          if (this.selectedCampusAds.length === 0 && component.data.campusAds && component.data.campusAds.length > 0) {
            this.loadSelectedCampusAds(component.data.campusAds)
          }
          break
      }
    },

    // 更新组件
    updateComponent(updatedComponent) {
      if (updatedComponent && updatedComponent.id) {
        const index = this.pageComponents.findIndex(c => c.id === updatedComponent.id)
        if (index !== -1) {
          this.pageComponents.splice(index, 1, updatedComponent)
          if (this.selectedComponent && this.selectedComponent.id === updatedComponent.id) {
            this.selectedComponent = updatedComponent
          }
        }
      } else {
        // 触发重新渲染
        this.$forceUpdate()
      }
      this.saveDraft()
    },

    // 删除组件
    deleteComponent(index) {
      this.pageComponents.splice(index, 1)
      if (this.selectedComponentIndex === index) {
        this.selectedComponent = null
        this.selectedComponentIndex = -1
      } else if (this.selectedComponentIndex > index) {
        this.selectedComponentIndex--
      }
      this.saveDraft()
    },

    // 删除选中的组件
    deleteSelectedComponent() {
      if (this.selectedComponentIndex >= 0) {
        this.deleteComponent(this.selectedComponentIndex)
        this.$message.success('组件已删除')
      }
    },

    // 获取组件名称
    getComponentName(type) {
      const names = {
        campus: '校区名称',
        search: '搜索框',
        banner: '轮播图',
        image: '图片',
        video: '视频',
        goods: '商品展示',
        'distribution-goods': '分销商品',
        quick: '快捷入口',
        entries: '功能入口',
        notice: '校区公告',
        recommend: '品牌推荐',
        text: '文本'
      }
      return names[type] || '未知组件'
    },

    // 获取组件图标
    getComponentIcon(type) {
      const component = this.componentList.find(c => c.type === type)
      return component ? component.icon : 'el-icon-help'
    },

    // 管理轮播图
    manageBanners() {
      this.bannerDialogVisible = true
    },

    // 管理商品
    manageGoods() {
      console.log('打开商品管理弹窗 - 传递的数据:', {
        currentCampusId: this.currentCampusId,
        isAdmin: this.isAdmin,
        campusListLength: this.campusList.length,
        campusList: this.campusList
      })
      this.goodsDialogVisible = true
    },

    // 管理快捷入口
    manageQuickEntries() {
      this.quickDialogVisible = true
    },

    // 管理功能入口
    manageFunctionEntries() {
      this.entriesDialogVisible = true
    },

    // 管理品牌推荐
    manageBrandRecommend() {
      this.recommendDialogVisible = true
    },

    // 管理分销商品
    manageDistributionGoods() {
      console.log('打开分销商品管理弹窗 - 传递的数据:', {
        currentCampusId: this.currentCampusId,
        isAdmin: this.isAdmin,
        campusListLength: this.campusList.length,
        selectedDistributionGoods: this.selectedDistributionGoods
      })
      this.distributionGoodsDialogVisible = true
    },

    // 处理轮播图选择
    handleBannerSelect(selectedBanners) {
      console.log('选择的轮播图:', selectedBanners)

      if (this.selectedComponent && this.selectedComponent.type === 'banner') {
        // 更新组件数据
        this.$set(this.selectedComponent.data, 'banners', selectedBanners.map(b => b.id))
        this.selectedBanners = selectedBanners

        // 更新页面组件数组中的对应项
        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        // 保存草稿
        this.saveDraft()

        this.$message.success(`已选择 ${selectedBanners.length} 张轮播图`)
        console.log('更新后的组件:', this.selectedComponent)
      }
      this.bannerDialogVisible = false
    },

    // 处理功能入口选择
    handleEntriesSelect(selectedEntries) {
      console.log('选择的功能入口:', selectedEntries)
      console.log('当前选中组件:', this.selectedComponent)

      if (this.selectedComponent && this.selectedComponent.type === 'entries') {
        this.$set(this.selectedComponent.data, 'entries', selectedEntries.map(e => e.id))
        this.selectedEntries = selectedEntries

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        console.log('更新后的组件数据:', this.selectedComponent.data)
        this.saveDraft()
        this.$message.success(`已选择 ${selectedEntries.length} 个功能入口`)
      }
      this.entriesDialogVisible = false
    },

    // 处理商品选择
    handleGoodsSelect(selectedGoods) {
      console.log('选择的商品:', selectedGoods)
      console.log('当前选中组件:', this.selectedComponent)

      if (this.selectedComponent && this.selectedComponent.type === 'goods') {
        this.$set(this.selectedComponent.data, 'goodsIds', selectedGoods.map(g => g.id))
        this.selectedGoods = selectedGoods

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        console.log('更新后的组件数据:', this.selectedComponent.data)
        this.saveDraft()
        this.$message.success(`已选择 ${selectedGoods.length} 个商品`)
      }
      this.goodsDialogVisible = false
    },

    // 处理品牌推荐选择
    handleRecommendSelect(selectedRecommends) {
      console.log('选择的品牌推荐:', selectedRecommends)
      console.log('当前选中组件:', this.selectedComponent)

      if (this.selectedComponent && this.selectedComponent.type === 'recommend') {
        this.$set(this.selectedComponent.data, 'brands', selectedRecommends.map(r => r.id))
        this.selectedRecommends = selectedRecommends

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        console.log('更新后的组件数据:', this.selectedComponent.data)
        this.saveDraft()
        this.$message.success(`已选择 ${selectedRecommends.length} 个品牌推荐`)
      }
      this.recommendDialogVisible = false
    },

    // 处理快捷入口选择
    handleQuickSelect(selectedQuicks) {
      console.log('选择的快捷入口:', selectedQuicks)

      if (this.selectedComponent && this.selectedComponent.type === 'quick') {
        this.$set(this.selectedComponent.data, 'entries', selectedQuicks.map(q => q.id))
        this.selectedQuicks = selectedQuicks

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        this.saveDraft()
        this.$message.success(`已选择 ${selectedQuicks.length} 个快捷入口`)
      }
      this.quickDialogVisible = false
    },

    // 处理分销商品选择
    handleDistributionGoodsSelect(selectedDistributionGoods) {
      console.log('选择的分销商品:', selectedDistributionGoods)

      if (this.selectedComponent && this.selectedComponent.type === 'distribution-goods') {
        this.$set(this.selectedComponent.data, 'goodsIds', selectedDistributionGoods.map(g => g.goodId))
        this.selectedDistributionGoods = selectedDistributionGoods

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        this.saveDraft()
        this.$message.success(`已选择 ${selectedDistributionGoods.length} 个分销商品`)
      }
      this.distributionGoodsDialogVisible = false
    },

    // 加载已选择的轮播图
    async loadSelectedBanners(bannerIds) {
      if (!bannerIds || bannerIds.length === 0) {
        return
      }

      try {
        // 调用API获取轮播图详情
        const response = await listBannerAds({ status: 1 })
        if (response && response.rows) {
          const newBanners = response.rows.filter(banner =>
            bannerIds.includes(banner.id) &&
            !this.selectedBanners.some(existing => existing.id === banner.id)
          )
          this.selectedBanners = [...this.selectedBanners, ...newBanners]
        } else {
          // 如果API调用失败，使用模拟数据
          const mockBanners = bannerIds
            .filter(id => !this.selectedBanners.some(existing => existing.id === id))
            .map(id => ({
              id: id,
              title: '轮播图 ' + id,
              image: '/placeholder.jpg',
              link: 'https://example.com',
              status: 1
            }))
          this.selectedBanners = [...this.selectedBanners, ...mockBanners]
        }
      } catch (error) {
        console.error('加载轮播图失败:', error)
        // 使用模拟数据作为fallback
        const mockBanners = bannerIds
          .filter(id => !this.selectedBanners.some(existing => existing.id === id))
          .map(id => ({
            id: id,
            title: '轮播图 ' + id,
            image: '/placeholder.jpg',
            link: 'https://example.com',
            status: 1
          }))
        this.selectedBanners = [...this.selectedBanners, ...mockBanners]
      }

      console.log('已加载选中的轮播图:', this.selectedBanners)
    },

    // 加载已选择的功能入口
    async loadSelectedEntries(entryIds) {
      if (!entryIds || entryIds.length === 0) {
        return
      }

      // 检查是否已经有对应的数据，如果有就跳过
      const existingIds = this.selectedEntries.map(entry => entry.id)
      const newIds = entryIds.filter(id => !existingIds.includes(id))

      if (newIds.length === 0) {
        return
      }

      // 暂时使用模拟数据
      const mockEntries = newIds.map(id => ({
        id: id,
        name: '功能入口 ' + id,
        builtInIcon: 'el-icon-menu',
        link: 'https://example.com',
        status: 1
      }))
      this.selectedEntries = [...this.selectedEntries, ...mockEntries]

      console.log('已加载选中的功能入口:', this.selectedEntries)
    },

    // 加载已选择的商品
    async loadSelectedGoods(goodsIds) {
      if (!goodsIds || goodsIds.length === 0) {
        return
      }

      // 检查是否已经有对应的数据，如果有就跳过
      const existingIds = this.selectedGoods.map(goods => goods.id)
      const newIds = goodsIds.filter(id => !existingIds.includes(id))

      if (newIds.length === 0) {
        return
      }

      // 暂时使用模拟数据
      const mockGoods = newIds.map(id => ({
        id: id,
        name: '商品 ' + id,
        image: '/placeholder.jpg',
        price: (Math.random() * 100 + 50).toFixed(2),
        link: 'https://example.com',
        status: 1
      }))
      this.selectedGoods = [...this.selectedGoods, ...mockGoods]

      console.log('已加载选中的商品:', this.selectedGoods)
    },

    // 加载已选择的品牌推荐
    async loadSelectedRecommends(brandIds) {
      if (!brandIds || brandIds.length === 0) {
        return
      }

      // 检查是否已经有对应的数据，如果有就跳过
      const existingIds = this.selectedRecommends.map(brand => brand.id)
      const newIds = brandIds.filter(id => !existingIds.includes(id))

      if (newIds.length === 0) {
        return
      }

      // 暂时使用模拟数据
      const mockBrands = newIds.map(id => ({
        id: id,
        name: '品牌 ' + id,
        logo: '/placeholder.jpg',
        link: 'https://example.com',
        status: 1
      }))
      this.selectedRecommends = [...this.selectedRecommends, ...mockBrands]

      console.log('已加载选中的品牌推荐:', this.selectedRecommends)
    },

    // 加载已选择的快捷入口
    async loadSelectedQuicks(quickIds) {
      if (!quickIds || quickIds.length === 0) {
        return
      }

      // 检查是否已经有对应的数据，如果有就跳过
      const existingIds = this.selectedQuicks.map(quick => quick.id)
      const newIds = quickIds.filter(id => !existingIds.includes(id))

      if (newIds.length === 0) {
        return
      }

      // 暂时使用模拟数据
      const mockQuicks = newIds.map(id => ({
        id: id,
        name: '快捷入口 ' + id,
        icon: 'el-icon-s-grid',
        link: 'https://example.com',
        status: 1
      }))
      this.selectedQuicks = [...this.selectedQuicks, ...mockQuicks]

      console.log('已加载选中的快捷入口:', this.selectedQuicks)
    },

    // 加载已选择的校区公告
    async loadSelectedCampusAds(campusIds) {
      if (!campusIds || campusIds.length === 0) {
        return
      }

      try {
        // 调用API获取校区公告详情
        const { listCampus } = await import('@/api/home/campus/campus')
        const response = await listCampus({ status: 1 })
        if (response && response.rows) {
          const newCampusAds = response.rows.filter(campus =>
            campusIds.includes(campus.id) &&
            !this.selectedCampusAds.some(existing => existing.id === campus.id)
          )
          this.selectedCampusAds = [...this.selectedCampusAds, ...newCampusAds]
        } else {
          // 如果API调用失败，使用模拟数据
          const mockCampusAds = campusIds
            .filter(id => !this.selectedCampusAds.some(existing => existing.id === id))
            .map(id => ({
              id: id,
              title: '校区公告 ' + id,
              content: '这是一条重要的校区公告内容...',
              tag: '重要公告',
              type: 'important',
              publishTime: new Date().toISOString(),
              status: 1
            }))
          this.selectedCampusAds = [...this.selectedCampusAds, ...mockCampusAds]
        }
      } catch (error) {
        console.error('加载校区公告失败:', error)
        // 使用模拟数据作为fallback
        const mockCampusAds = campusIds
          .filter(id => !this.selectedCampusAds.some(existing => existing.id === id))
          .map(id => ({
            id: id,
            title: '校区公告 ' + id,
            content: '这是一条重要的校区公告内容...',
            tag: '重要公告',
            type: 'important',
            publishTime: new Date().toISOString(),
            status: 1
          }))
        this.selectedCampusAds = [...this.selectedCampusAds, ...mockCampusAds]
      }

      console.log('已加载选中的校区公告:', this.selectedCampusAds)
    },

    // 拖拽结束
    onDragEnd() {
      this.saveDraft()
    },

    // 预览小程序
    previewMiniProgram() {
      this.pageData = {
        components: this.pageComponents,
        config: {
          title: '艺术教育小程序',
          backgroundColor: '#f5f5f5'
        }
      }

      console.log('预览数据:', this.pageData)
      this.$message.success('预览数据已生成，请查看控制台')
    },

    // 生成小程序代码
    generateCode() {
      this.pageData = {
        components: this.pageComponents,
        config: {
          title: '艺术教育小程序',
          backgroundColor: '#f5f5f5'
        }
      }

      this.codeDialogVisible = true
    },

    // 保存草稿
    saveDraft() {
      const draftData = {
        components: this.pageComponents,
        selectedData: {
          banners: this.selectedBanners,
          entries: this.selectedEntries,
          goods: this.selectedGoods,
          recommends: this.selectedRecommends,
          quicks: this.selectedQuicks,
          campusAds: this.selectedCampusAds,
          distributionGoods: this.selectedDistributionGoods
        },
        timestamp: Date.now()
      }

      localStorage.setItem('miniprogram_draft', JSON.stringify(draftData))
    },

    // 管理模板
    manageTemplates() {
      this.templateDialogVisible = true
    },

    // 处理加载模板
    handleLoadTemplate(templateData) {
      try {
        // 解析模板数据
        const data = typeof templateData === 'string' ? JSON.parse(templateData) : templateData

        // 加载组件配置
        if (data.components) {
          this.pageComponents = data.components
        }

        // 加载选中的数据
        if (data.selectedData) {
          this.selectedBanners = data.selectedData.banners || []
          this.selectedEntries = data.selectedData.entries || []
          this.selectedGoods = data.selectedData.goods || []
          this.selectedRecommends = data.selectedData.recommends || []
          this.selectedQuicks = data.selectedData.quicks || []
          this.selectedCampusAds = data.selectedData.campusAds || []
          this.selectedDistributionGoods = data.selectedData.distributionGoods || []
        }

        // 清除当前选中状态
        this.selectedComponent = null
        this.selectedComponentIndex = -1

        this.$message.success('模板加载成功')
        this.templateDialogVisible = false

        // 保存为草稿
        this.saveDraft()

      } catch (error) {
        console.error('加载模板失败:', error)
        this.$message.error('模板数据格式错误')
      }
    },

    // 加载模板卡片
    async loadTemplateCards() {
      this.templateCardsLoading = true
      try {
        const searchForm = {
          templateName: this.templateSearchName,
          campusId: this.isAdmin ? null : this.currentCampusId, // 非管理员只能看自己校区的模板
          pageNum: 1,
          pageSize: 100 // 加载更多，卡片展示
        }

        console.log('请求参数:', searchForm)
        console.log('当前用户校区ID:', this.currentCampusId)
        console.log('是否管理员:', this.isAdmin)

        const response = await listHomepageTemplate(searchForm)
        console.log('API响应:', response)

        this.templateCards = response.rows || []

        console.log('加载的模板卡片:', this.templateCards)
      } catch (error) {
        console.error('加载模板卡片失败:', error)
        console.log('错误详情:', error.response || error)
        this.$message.error('加载模板失败: ' + (error.message || '未知错误'))
      } finally {
        this.templateCardsLoading = false
      }
    },

    // 选择模板进入编辑
    async selectTemplate(template) {
      try {
        this.currentTemplateId = template.id

        // 加载模板数据
        const data = typeof template.templateData === 'string'
          ? JSON.parse(template.templateData)
          : template.templateData

        // 加载组件配置
        if (data.components) {
          this.pageComponents = data.components
        }

        // 加载选中的数据
        if (data.selectedData) {
          this.selectedBanners = data.selectedData.banners || []
          this.selectedEntries = data.selectedData.entries || []
          this.selectedGoods = data.selectedData.goods || []
          this.selectedRecommends = data.selectedData.recommends || []
          this.selectedQuicks = data.selectedData.quicks || []
          this.selectedCampusAds = data.selectedData.campusAds || []
          this.selectedDistributionGoods = data.selectedData.distributionGoods || []
        }

        // 切换到编辑界面
        this.showTemplateSelection = false
        this.selectedComponent = null
        this.selectedComponentIndex = -1

        this.$message.success(`已加载模板：${template.templateName}`)

      } catch (error) {
        console.error('加载模板失败:', error)
        this.$message.error('模板数据格式错误')
      }
    },

    // 返回模板选择界面
    backToTemplateSelection() {
      this.showTemplateSelection = true
      this.currentTemplateId = null
      this.loadTemplateCards()
    },

    // 新建模板
    createNewTemplate() {
      this.currentTemplateId = null
      this.pageComponents = []
      this.selectedBanners = []
      this.selectedEntries = []
      this.selectedGoods = []
      this.selectedRecommends = []
      this.selectedQuicks = []
      this.selectedCampusAds = []
      this.selectedDistributionGoods = []
      this.selectedComponent = null
      this.selectedComponentIndex = -1
      this.showTemplateSelection = false

      this.$message.success('已创建新模板，开始设计吧！')
    },

    // 保存当前模板
    async saveCurrentTemplate() {
      if (this.pageComponents.length === 0) {
        this.$message.warning('请先添加一些组件')
        return
      }

      const templateData = {
        components: this.pageComponents,
        selectedData: {
          banners: this.selectedBanners,
          entries: this.selectedEntries,
          goods: this.selectedGoods,
          recommends: this.selectedRecommends,
          quicks: this.selectedQuicks,
          campusAds: this.selectedCampusAds,
          distributionGoods: this.selectedDistributionGoods
        }
      }

      if (this.currentTemplateId) {
        // 更新现有模板
        try {
          await updateHomepageTemplate({
            id: this.currentTemplateId,
            templateData: JSON.stringify(templateData)
          })
          this.$message.success('模板保存成功')
        } catch (error) {
          console.error('保存模板失败:', error)
          this.$message.error('保存模板失败')
        }
      } else {
        // 创建新模板，需要输入名称
        this.$prompt('请输入模板名称', '保存模板', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '模板名称不能为空'
        }).then(async ({ value }) => {
          try {
            const response = await addHomepageTemplate({
              templateName: value,
              templateDesc: '通过设计器创建的模板',
              campusId: this.currentCampusId,
              templateData: JSON.stringify(templateData)
            })

            this.currentTemplateId = response.data || response.id // 保存返回的ID
            this.$message.success('模板创建成功')
          } catch (error) {
            console.error('创建模板失败:', error)
            this.$message.error('创建模板失败')
          }
        }).catch(() => {})
      }
    },

    // 处理模板操作
    async handleTemplateAction(command) {
      const { action, template } = command

      switch (action) {
        case 'copy':
          this.$prompt('请输入新模板名称', '复制模板', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputValue: template.templateName + ' (复制)',
            inputPattern: /\S+/,
            inputErrorMessage: '模板名称不能为空'
          }).then(async ({ value }) => {
            try {
              await copyTemplate(template.id, value)
              this.$message.success('模板复制成功')
              this.loadTemplateCards()
            } catch (error) {
              console.error('复制模板失败:', error)
              this.$message.error('复制模板失败')
            }
          }).catch(() => {})
          break

        case 'activate':
          try {
            await activateTemplate(template.id, template.campusId)
            this.$message.success('模板已启用')
            this.loadTemplateCards()
          } catch (error) {
            console.error('启用模板失败:', error)
            this.$message.error('启用模板失败')
          }
          break

        case 'delete':
          this.$confirm('确定要删除此模板吗？', '确认删除', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            try {
              await delHomepageTemplate([template.id])
              this.$message.success('删除成功')
              this.loadTemplateCards()
            } catch (error) {
              console.error('删除模板失败:', error)
              this.$message.error('删除失败')
            }
          }).catch(() => {})
          break
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) {
        return '今天'
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    },

    // 获取校区名称
    getCampusName(campusId) {
      const campus = this.campusList.find(c => c.campusId === campusId)
      return campus ? campus.campusName : '未知校区'
    },

    // Canvas点击事件
    handleCanvasClick(event) {
      // 如果点击的是画布背景，取消选择
      if (event.target === event.currentTarget) {
        this.selectedComponent = null
        this.selectedComponentIndex = -1
      }
    },

    // 管理校区公告
    manageCampusAds() {
      console.log('点击管理校区公告按钮')
      console.log('当前选中的校区公告:', this.selectedCampusAds)
      this.campusDialogVisible = true
      console.log('弹窗状态:', this.campusDialogVisible)
    },

    // 处理校区公告选择
    handleCampusSelect(selectedCampusAds) {
      console.log('选择的校区公告:', selectedCampusAds)

      if (this.selectedComponent && this.selectedComponent.type === 'notice') {
        this.$set(this.selectedComponent.data, 'campusAds', selectedCampusAds.map(a => a.id))
        this.selectedCampusAds = selectedCampusAds

        const componentIndex = this.pageComponents.findIndex(c => c.id === this.selectedComponent.id)
        if (componentIndex !== -1) {
          this.$set(this.pageComponents, componentIndex, { ...this.selectedComponent })
        }

        this.saveDraft()
        this.$message.success(`已选择 ${selectedCampusAds.length} 条校区公告`)
      }
      this.campusDialogVisible = false
    }
  }
}
</script>

<style scoped>
/* 工具栏样式 */
.toolbar-header {
  background: #fff;
  border-bottom: 1px solid #e1e6f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.toolbar-left h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 校区信息样式 */
.campus-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.campus-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

/* 左侧组件库样式 */
.component-library-aside {
  background: #fff;
  border-right: 1px solid #e1e6f0;
  box-shadow: 2px 0 8px rgba(0,0,0,0.08);
}

.component-library {
  padding: 20px;
  height: 100%;
}

.component-library h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.component-item:hover {
  background: #e3f2fd;
  border-color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.component-item i {
  margin-right: 12px;
  font-size: 18px;
  color: #409eff;
}

.component-item span {
  font-size: 14px;
  color: #2c3e50;
  font-weight: 500;
}

/* 中间画布样式 */
.canvas-main {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.canvas-area {
  display: flex;
  justify-content: center;
  align-items: center;
}

.phone-frame {
  width: 375px;
  height: 667px;
  background: linear-gradient(145deg, #1a1a1a, #2d2d2d);
  border-radius: 30px;
  padding: 15px;
  box-shadow:
    0 20px 50px rgba(0,0,0,0.4),
    0 0 0 1px rgba(255,255,255,0.1);
  position: relative;
}

.phone-frame::before {
  content: '';
  position: absolute;
  top: 50px;
  left: -3px;
  width: 3px;
  height: 30px;
  background: #333;
  border-radius: 2px;
}

.phone-frame::after {
  content: '';
  position: absolute;
  top: 90px;
  left: -3px;
  width: 3px;
  height: 50px;
  background: #333;
  border-radius: 2px;
}

.phone-header {
  height: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  padding: 0 20px;
  background: rgba(255,255,255,0.1);
  border-radius: 15px 15px 0 0;
}

.canvas-container {
  width: 345px;
  height: 622px;
  background: #fff;
  border-radius: 0 0 15px 15px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
}

.draggable-area {
  min-height: 100%;
  padding: 10px;
}

/* 组件过渡效果 */
.component-transition-move,
.component-transition-enter-active,
.component-transition-leave-active {
  transition: all 0.3s ease;
}

.component-transition-enter-from,
.component-transition-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.component-transition-leave-active {
  position: absolute;
}

/* 右侧配置面板样式 */
.config-aside {
  background: #fff;
  border-left: 1px solid #e1e6f0;
  box-shadow: -2px 0 8px rgba(0,0,0,0.08);
}

.config-panel {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.no-selection {
  text-align: center;
  color: #94a3b8;
  margin-top: 100px;
}

.no-selection i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #cbd5e1;
}

.no-selection p {
  font-size: 16px;
  margin-bottom: 8px;
  color: #64748b;
}

.no-selection small {
  font-size: 12px;
  color: #94a3b8;
  line-height: 1.5;
}

/* 配置区域样式 */
.config-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f1f5f9;
}

.config-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-section {
  margin-bottom: 24px;
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e2e8f0;
}

.config-section h4 {
  margin: 0 0 16px 0;
  color: #475569;
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
}

.config-form {
  margin-top: 16px;
}

.config-form .el-form-item {
  margin-bottom: 16px;
}

.config-form small {
  color: #94a3b8;
  font-size: 12px;
  margin-left: 4px;
}

.manage-btn {
  width: 100%;
  margin-bottom: 12px;
}

/* 轮播图预览样式 */
.banner-preview {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.banner-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.2s ease;
}

.banner-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.banner-item >>> .el-image {
  margin-right: 12px;
  border-radius: 4px;
}

.banner-item >>> .el-image img {
  border-radius: 4px;
}

.banner-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.banner-title {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
}

.banner-link {
  font-size: 11px;
  color: #94a3b8;
}

/* 校区公告预览样式 */
.campus-preview {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.campus-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.2s ease;
}

.campus-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.campus-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.campus-title {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.campus-tag {
  font-size: 11px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
  font-weight: 500;
}

.more-info {
  font-size: 12px;
  color: #666;
  text-align: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  margin-top: 8px;
}

/* 分销商品预览样式 */
.distribution-preview {
  margin-top: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.distribution-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.2s ease;
}

.distribution-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.distribution-item img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
}

.distribution-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.goods-title {
  font-size: 13px;
  color: #2c3e50;
  font-weight: 500;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-source {
  font-size: 11px;
  color: #409eff;
  background: #ecf5ff;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
  font-weight: 500;
}

/* 弹窗样式 */
.manage-dialog .el-dialog {
  border-radius: 12px;
}

.code-dialog .el-dialog {
  border-radius: 12px;
}

.template-dialog .el-dialog {
  border-radius: 12px;
}

.template-dialog .el-dialog__body {
  padding: 20px;
  max-height: 80vh;
  overflow: auto;
}

/* 简化的模板样式 */



/* 响应式设计 */
@media (max-width: 1400px) {
  .config-aside {
    width: 280px;
  }

  .component-library-aside {
    width: 200px;
  }

  .template-cards {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 1200px) {
  .phone-frame {
    width: 320px;
    height: 568px;
  }

  .canvas-container {
    width: 295px;
    height: 530px;
  }

  .template-selection-container {
    padding: 20px;
  }

  .template-cards {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .template-selection-toolbar {
    flex-direction: column;
    gap: 15px;
  }

  .template-cards {
    grid-template-columns: 1fr;
  }

  .template-selection-header h2 {
    font-size: 24px;
  }
}
</style>
